<?php


namespace App\Dao;


use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\ConfigOther;
use App\Utils\Log;

class ConfigOtherDao extends AbstractDao
{
    public function where(array $where): \Hyperf\Database\Model\Builder
    {
        $builder = ConfigOther::query();

        foreach ($where as $field => $value) {
            switch ($field) {
                default:
                    $builder->where($field, $value);
            }
        }

        return $builder;
    }


    /**
     * 获取抽成比例
     * @param int $cooperative_id
     * @return string
     */
    public function getCommissionPercent(int $cooperative_id)
    {
        /** @var ConfigOther $commissionPercent */
        $commissionPercent = $this->first(
            [
                'cooperative_id' => $cooperative_id,
                'name' => \App\Constants\Model\ConfigOther::CONFIG_COMMISSION_PERCENT_NAME
            ]
        );
        if (!$commissionPercent) {
            throw new BusinessException(ErrorCode::NOT_COMMISSION_PERCENT);
        }

        return bcdiv((string)$commissionPercent->val, '100', 2);
    }


    /**
     * 是否设置自动打款
     * @param int $cooperative_id
     * @return int
     */
    public function isAutoPayment(int $cooperative_id): int
    {
        /** @var ConfigOther $autoPayment */
        $autoPayment = $this->first(
            [
                'cooperative_id' => $cooperative_id,
                'name' => \App\Constants\Model\ConfigOther::CONFIG_AUTO_PAYMENT_NAME
            ]
        );

        if (!$autoPayment) {
            Log::get()->error(ErrorCode::NOT_AUTO_PAYMENT);
            Log::get()->error(-1, [$cooperative_id, ErrorCode::NOT_AUTO_PAYMENT]);
            throw new BusinessException(ErrorCode::NOT_AUTO_PAYMENT);
        }

        return $autoPayment->val;
    }


    /**
     * 获取客服电话
     * @param int $cooperative_id
     * @return string
     */
    public function getServicePhone(int $cooperative_id): string
    {
        /** @var ConfigOther $servicePhone */
        $servicePhone = $this->first(
            [
                'cooperative_id' => $cooperative_id,
                'name' => \App\Constants\Model\ConfigOther::CONFIG_SERVICE_PHONE_NAME
            ]
        );
        if (!$servicePhone) {
            return '';
        }
        return $servicePhone->val;
    }
}